﻿CREATE PROCEDURE [dbo].[InventoryDocInsert]
(--Инвентаризация
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @DocTypeId int,	@DepartmentUserId int
	SET NOCOUNT ON

IF @DocNumber Is Null
BEGIN
	EXEC [dbo].[GetNextDocNumber] 6, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 

--IF (@ContragentDocDate Is NOT Null) AND @ContragentDocDate > @DocDate
--BEGIN
--	SELECT @intErrCode = 2, 
--	@strMsg = 'Дата документа поставщика больше даты приходной накладной!'
--	RAISERROR (@strMsg, 11, 1)
--	RETURN @intErrCode
--END
SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], DepartmentUserId,
[Note], [MD], [MW]) 
VALUES (@intNextId, 6, @DocDate, @DocNumber, @DepartmentUserId,
@Note, @MD, @MW);
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
DepartmentUserId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)

RETURN 0